package student;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;
import java.util.*;

@WebServlet("/StudentExamQuestionsServlet")
public class StudentExamQuestionsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String examIdParam = request.getParameter("exam_id");

        // 验证考试ID参数
        if (examIdParam == null || examIdParam.trim().isEmpty()) {
            response.sendRedirect("student.jsp");
            return;
        }

        int examId;
        try {
            examId = Integer.parseInt(examIdParam);
        } catch (NumberFormatException e) {
            request.setAttribute("error", "无效的考试ID格式");
            request.getRequestDispatcher("student_exam.jsp").forward(request, response);
            return;
        }

        session.setAttribute("currentExamId", examId);

        // 获取学生ID
        Integer studentId = (Integer) session.getAttribute("student_id");
        if (studentId == null) {
            response.sendRedirect("student_login.jsp");
            return;
        }

        // 验证学生访问权限
        try {
            Connectmysql conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root", "root", "com.mysql.cj.jdbc.Driver");

            if (conn.open()) {
                // 验证学生权限
                String verifySql = "SELECT ec.class_id FROM exam_class ec " +
                        "JOIN student s ON ec.class_id = s.class_id " +
                        "WHERE ec.exam_id = ? AND s.student_id = ?";
                ResultSet verifyRs = conn.executeSql(verifySql, new Object[]{examId, studentId});

                if (!verifyRs.next()) {
                    request.setAttribute("error", "您没有权限参加此考试");
                    request.getRequestDispatcher("student_exam.jsp").forward(request, response);
                    return;
                }

                // 获取考试信息
                String examInfoSql = "SELECT e.exam_name, c.course_name, e.start_time, " +
                        "e.duration, e.status, e.total_score " +
                        "FROM exam e " +
                        "JOIN course c ON e.course_id = c.course_id " +
                        "WHERE e.exam_id = ?";
                ResultSet examInfoRs = conn.executeSql(examInfoSql, new Object[]{examId});

                if (examInfoRs.next()) {
                    request.setAttribute("exam_id", examId);
                    request.setAttribute("exam_name", examInfoRs.getString("exam_name"));
                    request.setAttribute("course_name", examInfoRs.getString("course_name"));
                    request.setAttribute("start_time", examInfoRs.getTimestamp("start_time"));
                    request.setAttribute("duration", examInfoRs.getInt("duration"));
                    request.setAttribute("status", examInfoRs.getInt("status"));
                    request.setAttribute("total_score", examInfoRs.getDouble("total_score"));
                } else {
                    request.setAttribute("error", "未找到考试信息");
                    request.getRequestDispatcher("student_exam.jsp").forward(request, response);
                    return;
                }

                // 获取考试题目
                String questionsSql = "SELECT q.question_id, q.question_text, q.option_a, q.option_b, " +
                        "q.option_c, q.option_d, q.correct_answer, q.score, eq.sort_order " +
                        "FROM exam_question eq " +
                        "JOIN question q ON eq.question_id = q.question_id " +
                        "WHERE eq.exam_id = ? " +
                        "ORDER BY eq.sort_order ASC";
                List<Map<String, Object>> questions = new ArrayList<>();
                ResultSet rs = conn.executeSql(questionsSql, new Object[]{examId});

                while (rs.next()) {
                    Map<String, Object> question = new HashMap<>();
                    question.put("question_id", rs.getInt("question_id"));
                    question.put("question_text", rs.getString("question_text"));
                    question.put("option_a", rs.getString("option_a"));
                    question.put("option_b", rs.getString("option_b"));
                    question.put("option_c", rs.getString("option_c"));
                    question.put("option_d", rs.getString("option_d"));
                    question.put("correct_answer", rs.getString("correct_answer"));
                    question.put("score", rs.getDouble("score"));
                    question.put("sort_order", rs.getInt("sort_order"));
                    questions.add(question);
                }

                if (questions.isEmpty()) {
                    request.setAttribute("error", "此考试没有题目");
                } else {
                    request.setAttribute("questions", questions);
                }
            } else {
                request.setAttribute("error", "数据库连接失败");
            }
        } catch (Exception e) {
            request.setAttribute("error", "加载考试题目失败: " + e.getMessage());
            e.printStackTrace();
        }

        // 转发到JSP
        request.getRequestDispatcher("exam.jsp").forward(request, response);
    }
}